import React, {useEffect, useRef, useState} from 'react';
import {Image, Text, View, TouchableWithoutFeedback, FlatList} from 'react-native';
import {chunkArray} from '../utils/jsUtils';
import stylesXS from '../styles/xs';
import stylesMD from '../styles/md';
import stylesLG from '../styles/lg';

import dimesA5 from '../styles/size/a5';
import dimesA5X2 from '../styles/size/a5x2';
import dimesA6 from '../styles/size/nom';

const FlatListTm = ({
  list,
  onItemPress,
  onItemLongPress,
  onCheckPress = item => {},
  bodyStyle,
  itemStyle,
  checkId,
  status = '',
  headerStatus,
  screenHeight,
  screenWidth,
}) => {
  const [numColumns, setNumColumns] = useState(6); // Default to 4 columns for portrait
  const [stickers, setStickers] = useState([]);
  useEffect(() => {
    const isLandscape = screenWidth > screenHeight;
    setNumColumns(isLandscape ? 6 : 4);
    setStickers(chunkArray(list, isLandscape ? 6 : 4));
  }, [list, screenHeight, screenWidth]);
  let wd = Math.round(screenWidth);
  const styles =
    wd === 1024 || wd === 1365
      ? stylesLG
      : wd === 994 || wd === 1325
      ? stylesMD
      : stylesXS;

  const nom = wd === 1024 || wd === 1365
      ? dimesA5X2
      : wd === 994 || wd === 1325
        ? dimesA5
        : dimesA6;
  
  const _renderItem = (item, index, isBottom) => {
    return (
      <View style={styles.justAlign}>
        <TouchableWithoutFeedback
          underlayColor={'#f5f5f5'}
          activeOpacity={0.75}
          onPress={() => {
            // if (status === 'create' || headerStatus) {
            //   onItemPress(item);
            // } else {
            //   onCheckPress(item);
            // }
            onItemPress(item);
          }}
          onLongPress={() => onItemPress(item)}>
          <View
            style={[
              styles.justAlign,
              itemStyle,
              (screenWidth < screenHeight && index % 4 === 3) ||
              (screenWidth > screenHeight && index % 6 === 5)
                ? {marginRight: 0}
                : null,
                isBottom ? {marginBottom: 0} : null,
            ]}>
            <View
              style={[
                status === 'create' ? styles.createItem : null,
                status === 'create' && checkId?.id === item?.id
                  ? {borderColor: '#000'}
                  : {borderColor: 'transparent'},
                styles.justAlign,
                {
                  width: styles.createItem.width - 3,

                  top:1,
                  
                }
              ]}>
              <Image
                style={[
                  styles.cardItemImg,
                  {
                    resizeMode: 'contain',
                    resizeMethod: 'resize',
                  },
                ]}
                source={
                  item?.id === 'new_create_group'
                    ? require('../../assets/ic_add_group.png')
                    : !item?.thumb_sticker
                    ? require('../../assets/ic_sticker-think.png')
                    : {uri: `file://${item?.thumb_sticker}`}
                }
              />
              
            </View>
           
            <Text
              allowFontScaling={false}
              style={styles.textItemFont}
              ellipsizeMode={'middle'}
              numberOfLines={1}>
              {item?.name}
            </Text>
            {status === 'content' && !headerStatus ? (
              <View style={styles.checkBtn}>
                {checkId.filter(ite => ite === item.id).length > 0 ? (
                  <Image
                    style={[
                      styles.checkBtnWH,
                      {
                        resizeMode: 'contain',
                      },
                    ]}
                    source={require('../../assets/ic_select_black.png')}
                  />
                ) : (
                  <Image
                    style={[
                      styles.checkBtnWH,
                      {
                        resizeMode: 'contain',
                      },
                    ]}
                    source={require('../../assets/ic_select_no.png')}
                  />
                )}
              </View>
            ) : null}
             {status === 'create' && checkId?.id === item?.id ?
           null: (<View
              style={[
                 styles.createItem,
                  {borderColor: 'white',
                    position:'absolute',
                    top:0,
                    left:0
                  }
                
              ]}
            />)}
          </View>
        </TouchableWithoutFeedback>
      </View>
    );
  };
  return (
    <View style={bodyStyle}>
      <View style={[styles.flexCenterWrap]}>
        <FlatList
          data={stickers}
          renderItem={(data) => {
            var item = data.item;
            console.log("FlatList renderItem:"+data.index);
            
            return (
              <View style={[styles.flexCenterWrap]}>
                {item && item.map((ite, indx) => _renderItem(ite, indx, data.index === stickers.length - 1))}
              </View>
            );
          }}
          initialNumToRender={numColumns}
          showsVerticalScrollIndicator={false}
          keyExtractor={(item, index) => index.toString()}
        />
      </View>
    </View>
  );
};

export default FlatListTm;
